package tgc.edu.examxy.web.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.examxy.custom.DataGridUtils;
import tgc.edu.examxy.custom.TablePageable;
import tgc.edu.examxy.entity.ArticleManagement;
import tgc.edu.examxy.entity.Committee;
import tgc.edu.examxy.entity.EvaluationInformation;
import tgc.edu.examxy.entity.Student;
import tgc.edu.examxy.security.User2;
import tgc.edu.examxy.service.ArticleManagementService;
import tgc.edu.examxy.service.CommitteeService;
import tgc.edu.examxy.service.StudentService;
import tgc.edu.examxy.web.form.StudentForm;
/***
 *同学录 
 * @author 936642284
 *
 */
@Controller
@RequestMapping(value = "/schoolmate")
public class SchoolmateController {
	@Autowired
	private StudentService studentservice;
	@Autowired
	private CommitteeService Committeeservice;
	@Autowired
	private ArticleManagementService aservice;
	/***
	 * 跳转同学录
	 * @return
	 */
	@RequestMapping(value = "/manage")
	private String manage() {
		return "schoolmate/manage";
	}
	
	/***
	 * 显示全部
	 * @param pageParam
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(TablePageable pageParam,StudentForm form,ModelMap map) {
		
		
		PageRequest pageable = pageParam.bulidPageRequest();
		Specification<Student> spec = buildSpec(form);
		Page<Student> page=studentservice.findAll(spec, pageable);
		map.put("search", form.getSearch());
		return DataGridUtils.buildResult(page);
	}

	
	/****
	 * 进行条件筛选
	 * @param form
	 * @return
	 */
	private Specification<Student> buildSpec(StudentForm form) {
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 user = (User2) auth.getPrincipal();
	    Student students = studentservice.findByUsername(user.getUsername());
		Specification<Student> specification = new Specification<Student>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(students.getTbClass().getId()!=null) {
					Predicate name = cb.equal(root.get("tbClass").get("id"), students.getTbClass().getId());
					rules.add(name);
				}
				Predicate name = cb.equal(root.get("type"),"已通过");
				rules.add(name);
				Predicate isuser = cb.equal(root.get("isUsed"), true);
				rules.add(isuser);
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
			
		
		/***
		 * 对条件查询
		 */
		if(StringUtils.hasText(form.getSearch())) {
			Specification<Student> specification1= new Specification<Student>() {

				private static final long serialVersionUID = 1L;

				@Override
				public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					HashSet<Predicate> rules=new HashSet<>();
					String search = form.getSearch();
					
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("name"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.equal(root.get("sex"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("bron"), search));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("politicstime"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("degree"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("speciality"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("workUnit"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("tbClass").get("name"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("position"), "%"+search+"%"));
					}
					return cb.or(rules.toArray(new Predicate[rules.size()]));
				}
				
			};
			return specification.and(specification1);
		}else {
			return specification;
		}
		
		
	}
	/****
	 * 查询
	 * @param form
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/search")
	private String search(StudentForm form,ModelMap map) {
		map.put("model",form);
		return "schoolmate/search";
	}
	/****
	 * 跳转分组名单
	 * @return
	 */
	@RequestMapping(value = "/group")
	private String home(ModelMap map) {
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 user = (User2) auth.getPrincipal();
	  
	    Student students = studentservice.findByUsername(user.getUsername());
	    String c = students.getGroupNumber();
	    if(students.getGroupNumber()==null) {
	    	c = "您未分组";
	    }else {
	    	c = "（你是第 "+students.getGroupNumber() +" 组成员)";
	    }
	    
	    map.put("c", c);
		return "schoolmate/group";
	}
	
	@RequestMapping(value="/grouppage")
	@ResponseBody
	public Object grouppage(TablePageable pageParam,StudentForm form) {
		PageRequest pageable = pageParam.bulidPageRequest();
		Specification<Student> spec = buildSpec1(form);
		Page<Student> page=studentservice.findAll(spec, pageable);
		return DataGridUtils.buildResult(page);
	}

	private Specification<Student> buildSpec1(StudentForm form) {
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 user = (User2) auth.getPrincipal();
	    Student students = studentservice.findByUsername(user.getUsername());
		Specification<Student> specification = new Specification<Student>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(students.getTbClass().getId()!=null) {
					Predicate name = cb.equal(root.get("tbClass").get("id"), students.getTbClass().getId());
					rules.add(name);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		if(StringUtils.hasText(form.getSearch())) {
			Specification<Student> specification1= new Specification<Student>() {

				private static final long serialVersionUID = 1L;

				@Override
				public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					HashSet<Predicate> rules=new HashSet<>();
					String search = form.getSearch();
					
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("name"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.equal(root.get("sex"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("siteNumber"), search));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("position"), "%"+search+"%"));
					}
					if(StringUtils.hasText(search)) {
						rules.add(cb.like(root.get("workUnit"), "%"+search+"%"));
					}
					
					return cb.or(rules.toArray(new Predicate[rules.size()]));
				}
				
			};
			return specification.and(specification1);
		}else {
			return specification;
		}
	}
	@RequestMapping(value = "/classcommittee")
	private String calsscommittee(ModelMap map) {
		List<ArticleManagement> a = aservice.findByType("班委会");
		for (int i = 0; i < a.size(); i++) {
			String content = a.get(i).getContent();
			content.replace("img", "img style='width:30%;'");
			String replace = content.replace("/jeecgs/", "/jeecgxy/");
			 a.get(i).setContent(replace);
		} 
		map.put("idone", a.get(0).getId());
		map.put("xyxz", a);
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 user = (User2) auth.getPrincipal();
	    Student students = studentservice.findByUsername(user.getUsername());
	    Specification<Committee> spec = buildSpecone(students);
	    List<Committee> com = Committeeservice.findAll(spec);
	    
	    Specification<Student> specstudent = buildStudent(students);
	    List<Student> commone = studentservice.findAll(specstudent);
	    map.put("tbclass", students.getTbClass().getName());
	    map.put("commone", commone);
	    map.put("commtwo", com);
	    map.put("student", students);
		return "schoolmate/classcommittee";
	}

	private Specification<Student> buildStudent(Student students) {
		Specification<Student> specification = new Specification<Student>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(students.getTbClass().getId()!=null) {
					Predicate name = cb.equal(root.get("tbClass").get("id"), students.getTbClass().getId());
					rules.add(name);
				}
				Predicate name = cb.equal(root.get("group1"), true);
				rules.add(name);
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}

	private Specification<Committee> buildSpecone(Student students) {
		Specification<Committee> specification = new Specification<Committee>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Committee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(students.getTbClass().getId()!=null) {
					Predicate name = cb.equal(root.get("tbClassId"), students.getTbClass().getId());
					rules.add(name);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}
}
